package com.hndzyu.yd;

import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.hndzyu.yd.base.BaseActivity;
import com.hndzyu.yd.base.BaseApplication;
import com.hndzyu.yd.bean.AD;
import com.hndzyu.yd.bean.UserBean;
import com.hndzyu.yd.home.HomeFragment;
import com.hndzyu.yd.my.MyFragment;
import com.hndzyu.yd.task.TaskFragment;
import com.hndzyu.yd.team.TeamFragment;
import com.hndzyu.yd.url.Path;
import com.hndzyu.yd.utils.AdPreference;
import com.hndzyu.yd.utils.BnfStartupAdPageDto;
import com.hndzyu.yd.utils.DownListener;
import com.hndzyu.yd.utils.DownloadUtil;
import com.hndzyu.yd.utils.InstallReceiver;
import com.hndzyu.yd.utils.OkHttpDownloadJsonUtil;
import com.hndzyu.yd.utils.SharedPreferencesUtils;
import com.hndzyu.yd.vip.VipFragment;
import com.tencent.bugly.beta.Beta;

import java.util.List;
import java.util.Random;

import xcs.ert.jlj.AdManager;
import xcs.ert.jlj.os.OffersManager;
import xcs.ert.jlj.os.df.DiyOfferWallManager;


public class MainActivity extends BaseActivity implements View.OnClickListener {
    private long exitTime = 0;

    private HomeFragment homeFragment;
    private TaskFragment taskFragment;
    private TeamFragment teamFragment;
    private MyFragment myFragment;
    private VipFragment vipFragment;
    private FragmentManager fragmentManager;
    FragmentTransaction fragmentTransaction;
    private ImageView homeiv;
    private TextView hometext;
    private ImageView taskiv;
    private TextView tasktext;
    private ImageView teamiv;
    private TextView teamtext;
    private ImageView myiv;
    private TextView mytext;
    private TextView viptext;
    private static final String HOME_FRAGMENT_KEY = "homeFragment";
    private static final String TASK_FRAGMENT_KEY = "taskFragment";
    private static final String TEAM_FRAGMENT_KEY = "teamFragment";
    private static final String MY_FRAGMENT_KEY = "myFragment";

    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Beta.init(getApplicationContext(), false);
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .init();

        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();

        option.setIsNeedAddress(true);
//可选，是否需要地址信息，默认为不需要，即参数为false
//如果开发者需要获得当前点的地址信息，此处必须为true
        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
//需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        mLocationClient.start();



        initView();
        getData();
        setChioceItem(0);
        // 初始化接口，应用启动的时候调用，参数：appId, appSecret, isEnableYoumiLog
        AdManager.getInstance(this).init("676d75669c69d255", "2fa8bdefc7864577", true);
        // (可选) 检查积分墙源数据配置
        DiyOfferWallManager.getInstance(this).checkDiyOffersAdConfig();
        // 请务必调用以下代码，告诉积分墙源数据SDK应用启动，可以让SDK进行一些初始化操作。该接口务必在SDK的初始化接口之后调用。
        DiyOfferWallManager.getInstance(this).onAppLaunch();
        // (可选) 服务器回调积分配置
        OffersManager.getInstance(this).setCustomUserId(UserBean.uid + "");
        OffersManager.getInstance(this).setUsingServerCallBack(true);
//        // （可选）注册积分订单赚取监听（sdk v4.10版本新增功能）
//        PointsManager.getInstance(this).registerPointsEarnNotify(this);
//        if (savedInstanceState != null) {
//            /*获取保存的fragment  没有的话返回null*/
//            homeFragment = (HomeFragment) getSupportFragmentManager().getFragment(savedInstanceState, HOME_FRAGMENT_KEY);
//            taskFragment = (TaskFragment) getSupportFragmentManager().getFragment(savedInstanceState, TASK_FRAGMENT_KEY);
//            teamFragment = (TeamFragment) getSupportFragmentManager().getFragment(savedInstanceState, TEAM_FRAGMENT_KEY);
//            myFragment   =    (MyFragment) getSupportFragmentManager().getFragment(savedInstanceState, MY_FRAGMENT_KEY);
//        } else {
//        }
        OkHttpDownloadJsonUtil.downloadJson(this, Path.BASE_URL+"/index.php/index/index/gaoPic", new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {

            @Override
            public void onsendJson(String json) {
                try {
                    Gson gson = new Gson();
                    List<AD.DataBean> list = gson.fromJson(json, AD.class).getData();
                    if (!list.isEmpty()) {
                        AD.DataBean ad = list.get(0);
                        if (list.size() > 1) {
                            ad = list.get(new Random().nextInt(list.size()));
                        }
                        AdPreference.getInstance().saveStartupAdPage(new BnfStartupAdPageDto(Path.BASE_URL + ad.getGaopic(), ad.getGaourl(), "1536809117"));
                        new DownloadUtil().downloadImg(Environment.getExternalStorageDirectory() + "/MFAdYD/", Path.BASE_URL + ad.getGaopic(), new DownListener() {
                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onProgress(int currentLength) {

                            }

                            @Override
                            public void onFinish(String localPath) {

                            }

                            @Override
                            public void onFailure() {
                                AdPreference.getInstance().clear();
                            }
                        });

                    }
                } catch (Exception e) {
                }
            }
        });
    }

    @Override
    protected void initView() {
        findViewById(R.id.ll_main_tab_home).setOnClickListener(this);
        findViewById(R.id.ll_main_tab_task).setOnClickListener(this);
        findViewById(R.id.ll_main_tab_team).setOnClickListener(this);
        findViewById(R.id.ll_main_tab_my).setOnClickListener(this);
        findViewById(R.id.ll_main_tab_vip).setOnClickListener(this);
        homeiv = findViewById(R.id.home_iv);
        hometext = findViewById(R.id.home_text);
        taskiv = findViewById(R.id.task_iv);
        tasktext = findViewById(R.id.task_text);
        teamiv = findViewById(R.id.team_iv);
        teamtext = findViewById(R.id.team_text);
        myiv = findViewById(R.id.my_iv);
        mytext = findViewById(R.id.my_text);
        viptext = findViewById(R.id.vip_text);
        fragmentManager = getSupportFragmentManager();
//        setChioceItem(0); // 初始化页面加载时显示第一个选项卡

    }

    @Override
    protected void getData() {
        UserBean.uid = (int) SharedPreferencesUtils.getParam(this, "uid", 0);
        UserBean.pid = (int) SharedPreferencesUtils.getParam(this, "pid", 0);
        UserBean.headimg = (String) SharedPreferencesUtils.getParam(this, "headimg", "");
        UserBean.mobile = (String) SharedPreferencesUtils.getParam(this, "mobile", "");
        UserBean.nickname = (String) SharedPreferencesUtils.getParam(this, "nickname", "");
        UserBean.sex = (String) SharedPreferencesUtils.getParam(this, "sex", "");
        UserBean.birthday = (String) SharedPreferencesUtils.getParam(this, "birthday", "");
        UserBean.job = (String) SharedPreferencesUtils.getParam(this, "job", "");
        UserBean.balance = (String) SharedPreferencesUtils.getParam(this, "balance", "");
        UserBean.level = (int) SharedPreferencesUtils.getParam(this, "level", 0);
        UserBean.gao = (int) SharedPreferencesUtils.getParam(this, "gao", 0);
        UserBean.divide = (String) SharedPreferencesUtils.getParam(this, "divide", "");
        UserBean.vipdivide = (String) SharedPreferencesUtils.getParam(this, "vipdivide", "");
        UserBean.carddivide = (String) SharedPreferencesUtils.getParam(this, "carddivide", "");
        UserBean.vipcarddivide = (String) SharedPreferencesUtils.getParam(this, "vipcarddivide", "");
        UserBean.wx = (String) SharedPreferencesUtils.getParam(this, "wx", "");
        UserBean.appopenid = (String) SharedPreferencesUtils.getParam(this, "appopenid", "0");
        UserBean.qudao = (String) SharedPreferencesUtils.getParam(this, "qudao", "0");
        UserBean.ip = (String) SharedPreferencesUtils.getParam(this, "ip", "");
        UserBean.subnum = (int) SharedPreferencesUtils.getParam(this, "subnum", 200);
        UserBean.subprice = (String) SharedPreferencesUtils.getParam(this, "subprice", "2");

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_main_tab_home:
                setChioceItem(0);
                break;
            case R.id.ll_main_tab_task:
                setChioceItem(1);
                break;
            case R.id.ll_main_tab_team:
                setChioceItem(2);
                break;
            case R.id.ll_main_tab_my:
                setChioceItem(3);
                break;
            case R.id.ll_main_tab_vip:
//                if (UserBean.gao != 0) {
//                    setChioceItem(4);
//                } else {
//                    if (UserBean.level>0){
                        setChioceItem(4);
//                    }else {
//                        final MakeMoneyDialog makeDIalog = new MakeMoneyDialog(this);
//                        makeDIalog.setListener(new MakeMoneyDialog.MakeMoneyListener() {
//                            @Override
//                            public void checktrue() {
//                                startActivity(new Intent(MainActivity.this, TiXianActivity.class));
//                                makeDIalog.dismiss();
//
//                            }
//                        });
//                        makeDIalog.show();
//                        makeDIalog.setInto();
//                    }
//                }
                break;
            default:
                break;

        }
    }

    /**
     * 设置点击选项卡的事件处理
     *
     * @param index 选项卡的标号：0, 1, 2, 3
     */
    private void setChioceItem(int index) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        clearChioce(); // 清空, 重置选项, 隐藏所有Fragment
        hideFragments(fragmentTransaction);
        switch (index) {
            case 0:
                hometext.setTextColor(getResources().getColor(R.color.blue));
                homeiv.setImageResource(R.mipmap.icon_home2);
                // 如果homeFragment为空，则创建一个并添加
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                    fragmentTransaction.add(R.id.frame_layout, homeFragment);
                } else {
                    // 如果不为空，则直接显示
                    fragmentTransaction.show(homeFragment);
                }
                homeFragment.setOnButtonClick(new HomeFragment.OnButtonClick() {
                    @Override
                    public void onClick(int i,int position) {
                        if (taskFragment==null){
                            BaseApplication.taskposition=position;
                            setChioceItem(i);
                        }else {
                            setChioceItem(i);
                            taskFragment.selectTab(position);
                        }
                    }
                });
                break;
            case 1:
                tasktext.setTextColor(getResources().getColor(R.color.blue));
                taskiv.setImageResource(R.mipmap.icon_task2);

                if (taskFragment == null) {
                    taskFragment = new TaskFragment();
                    fragmentTransaction.add(R.id.frame_layout, taskFragment);
                } else {
                    fragmentTransaction.show(taskFragment);
                }
                break;
            case 2:
                teamtext.setTextColor(getResources().getColor(R.color.blue));
                teamiv.setImageResource(R.mipmap.icon_team2);
                if (teamFragment == null) {
                    teamFragment = new TeamFragment();
                    fragmentTransaction.add(R.id.frame_layout, teamFragment);
                } else {
                    fragmentTransaction.show(teamFragment);
                }
                break;
            case 3:
                mytext.setTextColor(getResources().getColor(R.color.blue));
                myiv.setImageResource(R.mipmap.icon_my2);
                if (myFragment == null) {
                    myFragment = new MyFragment();
                    fragmentTransaction.add(R.id.frame_layout, myFragment);
                } else {
                    fragmentTransaction.show(myFragment);
                }
                break;
            case 4:
                viptext.setTextColor(getResources().getColor(R.color.blue));
                if (vipFragment == null) {
                    vipFragment = new VipFragment();
                    fragmentTransaction.add(R.id.frame_layout, vipFragment);
                } else {
                    fragmentTransaction.show(vipFragment);
                }
                break;
                default:
                    break;
        }
        fragmentTransaction.commit();
    }

    /**
     * 当选中其中一个选项卡时，其他选项卡重置为默认
     */
    private void clearChioce() {
        hometext.setTextColor(getResources().getColor(R.color.color_huise));
        tasktext.setTextColor(getResources().getColor(R.color.color_huise));
        teamtext.setTextColor(getResources().getColor(R.color.color_huise));
        mytext.setTextColor(getResources().getColor(R.color.color_huise));
        viptext.setTextColor(getResources().getColor(R.color.color_huise));
        homeiv.setImageResource(R.mipmap.icon_home1);
        taskiv.setImageResource(R.mipmap.icon_task1);
        teamiv.setImageResource(R.mipmap.icon_team1);
        myiv.setImageResource(R.mipmap.icon_my1);

    }

    /**
     * 隐藏Fragment
     *
     * @param fragmentTransaction
     */
    private void hideFragments(FragmentTransaction fragmentTransaction) {
        if (homeFragment != null) {
            fragmentTransaction.hide(homeFragment);
        }
        if (taskFragment != null) {
            fragmentTransaction.hide(taskFragment);
        }
        if (teamFragment != null) {
            fragmentTransaction.hide(teamFragment);
        }
        if (myFragment != null) {
            fragmentTransaction.hide(myFragment);
        }
        if (vipFragment != null) {
            fragmentTransaction.hide(vipFragment);
        }
    }

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    @Override
    protected void onDestroy() {
        if (installedReceiver != null) {
            this.unregisterReceiver(installedReceiver);
        }
        super.onDestroy();
        // 请务必在应用退出的时候调用以下代码，告诉SDK应用已经关闭，可以让SDK进行一些资源的释放和清理。
        DiyOfferWallManager.getInstance(this).onAppExit();
//        // （可选）注销积分订单赚取监听-如果在onCreate中注册了，那这里必须得注销（sdk v4.10版本新增功能）
//        PointsManager.getInstance(this).unRegisterPointsEarnNotify(this);
        ImmersionBar.with(this).destroy(); //必须调用该方法，防止内存泄漏
    }

//    /**
//     * 积分订单赚取时会回调本方法（本方法执行在UI线程中）
//     */
//    @Override
//    public void onPointEarn(final Context context, EarnPointsOrderList list) {
//        for (int i = 0; i < list.size(); ++i) {
//            final EarnPointsOrderInfo info = list.get(i);
//            final String sig = md5("c43c24b4c104e86d" + "||" + info.getOrderID() + "||"  + UserBean.uid).substring(12,20);
////            Log.i("_________path",Path.ORDER(info.getOrderID(), "szz", info.getAppName(), "com.shizhanzhe.zxb", UserBean.uid + "", "10086", info.getPoints() + "", "0", info.getSettlingTime()/1000 + "", "0", info.getWadid()+"", "0", sig));
//            OkHttpDownloadJsonUtil.downloadJson(this, Path.ORDER(info.getOrderID(), "szz", info.getAppName(), "com.shizhanzhe.zxb", UserBean.uid + "", "10086", info.getPoints() + "", "0", info.getSettlingTime()/1000 + "", "0", info.getWadid()+"", "0", sig), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
//                @Override
//                public void onsendJson(String json) {
////                    Log.i("_________",json);
//                    try {
//                        JSONObject object = new JSONObject(json);
//                        if (object.optString("info").contains("完成")){
//                            Toast.makeText(getApplicationContext(), info.getAppName()+"完成", Toast.LENGTH_SHORT).show();
//                        }else {
//                            Toast.makeText(getApplicationContext(), info.getMessage(), Toast.LENGTH_SHORT).show();
//                        }
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//            });
////            Log.i("________", info.getMessage()+"______"+info.getAppName()+"_____"+info.getCustomUserID()+"_____"+info.getOrderID()+"_____"+info.getPoints()+"_____"+info.getStatus()+"_____"+info.getWadid()+"____"+info.getSettlingTime()+"___"+info.getChannelId());
//        }
//    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        /*fragment不为空时 保存*/
//        if (homeFragment != null) {
//            getSupportFragmentManager().putFragment(outState, HOME_FRAGMENT_KEY, homeFragment);
//        }
//        if (taskFragment != null) {
//            getSupportFragmentManager().putFragment(outState, TASK_FRAGMENT_KEY, taskFragment);
//        }
//        if (teamFragment != null) {
//            getSupportFragmentManager().putFragment(outState, TEAM_FRAGMENT_KEY, teamFragment);
//        }
//        if (taskFragment != null) {
//            getSupportFragmentManager().putFragment(outState, MY_FRAGMENT_KEY, taskFragment);
//        }
//        super.onSaveInstanceState(outState);

    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location){
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取地址相关的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

            String addr = location.getAddrStr();    //获取详细地址信息
            String country = location.getCountry();    //获取国家
            String province = location.getProvince();    //获取省份
            String city = location.getCity();    //获取城市
            String district = location.getDistrict();    //获取区县
            String street = location.getStreet();    //获取街道信息
//            Log.i("___________",province+city);
            mLocationClient.stop();
            try {
                OkHttpDownloadJsonUtil.downloadJson(MainActivity.this, Path.BASE_URL+"/index.php/index/index/position?uid=" + UserBean.uid + "&position=" + province + "," + city, new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                    @Override
                    public void onsendJson(String json) {

                    }
                });
            }catch (Exception e){

            }




        }
    }




    InstallReceiver installedReceiver;

    @Override
    public void onStart() {
        super.onStart();

        installedReceiver = new InstallReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.PACKAGE_ADDED");
        filter.addAction("android.intent.action.PACKAGE_REPLACED");
        filter.addDataScheme("package");

        this.registerReceiver(installedReceiver, filter);
    }

}
